/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.yuecai.modules.yc_goods.service;


import com.yuecai.modules.security.JwtUserDto;
import com.yuecai.modules.yc_category.vo.YcGoodsDetails;
import com.yuecai.modules.yc_category.vo.YcGoodsVo;
import com.yuecai.modules.yc_goods.domain.YcGoods;
import com.yuecai.modules.yc_goods.repository.YcGoodsRepository;
import com.yuecai.modules.yc_goods.service.dto.GoodDto;
import com.yuecai.modules.yc_goods.service.dto.YcGoodsDto;
import com.yuecai.modules.yc_goods.service.dto.YcGoodsQueryCriteria;
import com.yuecai.modules.yc_goods.service.mapstruct.YcGoodsMapper;
import com.yuecai.modules.yc_goods_sku.domain.YcGoodsSku;
import com.yuecai.modules.yc_goods_sku.repository.YcGoodsSkuRepository;
import com.yuecai.modules.yc_goods_sku.service.dto.YcGoodsSkuDto;
import com.yuecai.modules.yc_goods_sku.service.mapstruct.YcGoodsSkuMapper;
import com.yuecai.utils.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dm
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2020-06-24
 **/
@Service
@RequiredArgsConstructor
public class YcGoodsService {

    private final YcGoodsRepository ycGoodsRepository;
    private final YcGoodsSkuRepository ycGoodsSkuRepository;
    private final YcGoodsMapper ycGoodsMapper;
    private final YcGoodsSkuMapper ycGoodsSkuMapper;


    public Map<String, Object> queryAll(YcGoodsQueryCriteria criteria, Pageable pageable) {
        Page<YcGoods> page = ycGoodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(ycGoodsMapper::toDto));
    }

    public Map<String, Object> findYcGoodsVOs(YcGoodsQueryCriteria criteria, Pageable pageable) {
        JwtUserDto currentUser = (JwtUserDto) SecurityUtils.getCurrentUser();
        boolean realName = false;
        if (currentUser!=null){
            realName = currentUser.getUser().isRealName();
        }
        Page<YcGoods> page = ycGoodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<YcGoods> content = page.getContent();
        ArrayList<YcGoodsVo> list = new ArrayList<>();
        for (YcGoods ycGoods : content) {
            List<YcGoodsSku> byYcGoods = ycGoodsSkuRepository.findByYcGoods(ycGoods);
            if (CollectionUtils.isNotEmpty(byYcGoods)) {
                List<BigDecimal> collect = byYcGoods.stream().map(YcGoodsSku::getSellPrice).collect(Collectors.toList());
                BigDecimal min = Collections.min(collect);
                YcGoodsVo vo = new YcGoodsVo();
                BeanUtils.copyProperties(ycGoods, vo);
                vo.setSellPrice(min);
                if (!realName) {
                    vo.setOriginalPrice(null);
                    vo.setVipDiscount(null);
                    vo.setSellPrice(null);
                }
                list.add(vo);
            }
        }
        return PageUtil.toPageCu(page, list);
    }

    public List<YcGoodsDto> queryAll(YcGoodsQueryCriteria criteria) {
        return ycGoodsMapper.toDto(ycGoodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }


    @Transactional
    public YcGoodsDto findById(Long id) {
        YcGoods ycGoods = ycGoodsRepository.findById(id).orElseGet(YcGoods::new);
        ValidationUtil.isNull(ycGoods.getId(), "YcGoods", "id", id);
        return ycGoodsMapper.toDto(ycGoods);
    }


    @Transactional
    public YcGoodsDetails findByIdYcGoodsVo(Long id) throws Exception {
        Optional<YcGoods> byId = ycGoodsRepository.findById(id);
        if (byId.isPresent()) {
            YcGoods ycGoods = byId.get();
            YcGoodsDetails vo = new YcGoodsDetails();
            BeanUtils.copyProperties(ycGoods, vo);
            String sliderImage = vo.getSliderImage();
            String substring = sliderImage.substring(1, sliderImage.length() - 1);
            String[] split = null;
            if (!substring.equals("")) {
                split = substring.split(",");
            }
            vo.setSliderImages(split);
            return vo;
        }
        throw new Exception("该商品不存在！");
    }

    public static void main(String[] args) {
        String v = "[]";
        String substring = v.substring(0, v.length() - 1);
        String[] split = substring.split(",");
        System.out.println(substring + "-----");
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> create(GoodDto resources) {
        YcGoods ycGoods = new YcGoods();
        BeanUtils.copyProperties(resources, ycGoods);
        YcGoods goods = ycGoodsRepository.save(ycGoods);
        List<YcGoodsSku> skus = resources.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {
            for (YcGoodsSku ycGoodsSku : skus) {
                ycGoodsSku.setYcGoods(goods);
            }
            ycGoodsSkuRepository.saveAll(skus);
        }
        return ResponseEntity.ok("添加成功");
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(GoodDto resources) {
        YcGoods ycGoods = new YcGoods();
        BeanUtils.copyProperties(resources, ycGoods);
        YcGoods goods = ycGoodsRepository.save(ycGoods);
        List<YcGoodsSku> skus = resources.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {
            for (YcGoodsSku ycGoodsSku : skus) {
                ycGoodsSku.setYcGoods(goods);
            }
            ycGoodsSkuRepository.saveAll(skus);
        }
        ycGoodsRepository.save(ycGoods);
    }


    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ycGoodsRepository.deleteById(id);
        }
    }


    public void download(List<YcGoodsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcGoodsDto ycGoods : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("主图", ycGoods.getImg());
            map.put("轮播图", ycGoods.getSliderImage());
            map.put("商品名称", ycGoods.getName());
            map.put("商品简介", ycGoods.getToreInfo());
            map.put("活动ID", ycGoods.getActivityId());
            map.put("分类id", ycGoods.getCategoryId());
            map.put("原价", ycGoods.getOriginalPrice());
            map.put("vip折扣 例：八折填80", ycGoods.getVipDiscount());
            map.put("虚拟销量", ycGoods.getFicti());
            map.put("上下架状态1.上架 0.下架", ycGoods.getStatus());
            map.put("供应商ID", ycGoods.getSupplierId());
            map.put("品牌ID", ycGoods.getBrandId());
            map.put("商品详情", ycGoods.getIntroduction());
            map.put("创建时间", ycGoods.getCreateTime());
            map.put("更新时间", ycGoods.getUpdateTime());
            map.put("邮费(暂时不用)", ycGoods.getPostage());
            map.put("运费模板ID（暂时不用）", ycGoods.getTempId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public List<YcGoods> findByGoodName(String name) {
        List<YcGoods> ycGoods = ycGoodsRepository.findByNameLikeAndStatusTrue(name);
        if (ycGoods.size() > 5) {
            List<YcGoods> newList = ycGoods.subList(0, 5);//取前四条数据
            return newList;//返回新的list
        }
        return ycGoods;
    }

    public List<YcGoodsSkuDto> details(Long goodId) throws Exception {

        YcGoods goods = ycGoodsRepository.findByIdAndStatusTrue(goodId);
        if (goods == null) {
            throw new Exception("该商品未上架或不存在");
        }
        List<YcGoodsSku> byYcGoods = ycGoodsSkuRepository.findByYcGoods(goods);
        //return byYcGoods;
        return ycGoodsSkuMapper.toDto(byYcGoods);
    }

}